package no.ntnu.fp.handlers;

import java.io.IOException;
import java.net.ConnectException;
import java.util.List;

import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.AppointmentsForEmployeeMessage;
import no.ntnu.fp.messages.impl.RequestAppointmentsForEmployeeMessage;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.services.AppointmentService;

public class RequestAppointmentsForEmployeeHandler implements Handler {
	private final AppointmentService appointmentService;
	
	public RequestAppointmentsForEmployeeHandler(
			AppointmentService appointmentService) {
		this.appointmentService = appointmentService;
	}

	@Override
	public void handleMessage(Message message) {
		RequestAppointmentsForEmployeeMessage request = 
			(RequestAppointmentsForEmployeeMessage) message;
		
		Employee employee = request.getEmployee();
		
		List<Appointment> appointments 
				= appointmentService.getApppointmentsByEmployee(employee);
		
		AppointmentsForEmployeeMessage reply 
				= new AppointmentsForEmployeeMessage(employee, appointments);
		
		Connection connection = ReceiveWorker.getThreadLocalConnection();
		
		try {
			connection.send(reply.toString());
		} catch (IOException e) {
			throw new NetworkException(
					"Could not send appointments for employee " + employee, e);
		}
		
	}

}
